class_name Battle
extends Node2D

@export var battle_stats: BattleStats
@export var char_stats: CharacterStats
@export var music: AudioStream
@export var relics: RelicHandler

@onready var battle_ui: BattleUI = $BattleUI 
@onready var player_handler: PlayerHandler = $PlayerHandler
@onready var enemy_handler: EnemyHandler = $EnemyHandler
@onready var player: Player = $Player 

#测试控制
#var test:SimpleTest

# 资源调度器
var resource_scheduler: ResourceScheduler

# 回合管理
var current_turn: int = 0
var current_phase: int = TurnPhaseConstants.PLAYER_START


func _ready() -> void:
	# 添加到battle组中，方便其他节点查找
	add_to_group("battle")

	# 初始化资源调度器
	resource_scheduler = ResourceScheduler.new()
	add_child(resource_scheduler)
	
	# 连接调度器的效果触发信号
	resource_scheduler.resource_effect_triggered.connect(_on_scheduler_effect_triggered)
	
	# 初始化simple_test验证
	#test = SimpleTest.new()
	#add_child(test)
	#print("🔧 SimpleTest验证系统已初始化")
	
	enemy_handler.child_order_changed.connect(_on_enemies_child_order_changed)
	Events.enemy_turn_ended.connect(_on_enemy_turn_ended)
	
	Events.player_turn_ended.connect(_on_player_turn_ended)
	Events.player_hand_discarded.connect(_on_player_hand_discarded)
	Events.player_died.connect(_on_player_died)

func _on_scheduler_effect_triggered(effect: ScheduledEffect, target: Node) -> void:
	# 调度效果触发时的处理
	var target_name = target.name if target else "null"
	print("🎯 Battle: 调度效果触发 - %s 作用于 %s" % [effect.id, target_name])
	
	# 验证simple_test是否正常工作
#	if test and is_instance_valid(test):
#		print("✅ SimpleTest验证系统运行正常")
#		print("❌ SimpleTest验证系统异常")

func _input(event: InputEvent) -> void:
	if event.is_action_pressed("ui_accept"):
		var card_ui = player_handler.hand.get_child(0) as CardUI
		card_ui.card.cost -= 1
		card_ui.card = card_ui.card

func start_battle() -> void:
	get_tree().paused = false
	MusicPlayer.play(music, true)
	
	battle_ui.char_stats = char_stats
	player.stats = char_stats
	player_handler.relics = relics
	enemy_handler.setup_enemies(battle_stats)
	enemy_handler.reset_enemy_actions()

	
	# 发出battle_started信号
	Events.battle_started.emit(self)
	
	relics.relics_activated.connect(_on_relics_activated)
	relics.activate_relics_by_type(Relic.Type.START_OF_COMBAT)

func _on_enemies_child_order_changed() -> void:
	if enemy_handler.get_child_count() == 0 and is_instance_valid(relics):
		relics.activate_relics_by_type(Relic.Type.END_OF_COMBAT)

func _on_enemy_turn_ended() -> void:
	# 敌人回合结束，进入ENEMY_END阶段
	# 注意：此时所有敌人行动已完成，acting_enemies为空
	current_phase = TurnPhaseConstants.ENEMY_END
	print("🔄 敌人回合结束，进入ENEMY_END阶段")
	Events.turn_phase_changed.emit(current_turn, current_phase, enemy_handler)
	
	# 等待一帧确保ENEMY_END阶段效果处理完成
	await get_tree().process_frame
	
	# 然后开始玩家回合
	current_turn += 1
	print("🔄 开始玩家回合 %d" % current_turn)
	
	player_handler.start_turn()
	enemy_handler.reset_enemy_actions()

func _on_player_turn_ended() -> void:
	print("🔄 Battle._on_player_turn_ended() 被调用")
	# 玩家回合结束，触发PLAYER_END阶段
	current_phase = TurnPhaseConstants.PLAYER_END
	print("🔄 设置当前阶段为 PLAYER_END (%d)" % current_phase)
	
	# 发出回合阶段变化信号
	Events.turn_phase_changed.emit(current_turn, current_phase, player)
	print("🔄 已发出 PLAYER_END 阶段变化信号")
	
	# 调用玩家处理器的结束回合逻辑
	player_handler.end_turn()

func _on_player_hand_discarded() -> void:
	# 玩家手牌丢弃，开始敌人回合
	current_phase = TurnPhaseConstants.ENEMY_START
	
	# 发出回合阶段变化信号
	Events.turn_phase_changed.emit(current_turn, current_phase, enemy_handler)
	
	# 敌人回合开始
	enemy_handler.start_turn()

func _on_player_died() -> void:
	Events.battle_over_screen_requested.emit("game over", BattleOverPanel.Type.LOSE)
	SaveGame.delete_data()


func _on_relics_activated(type: Relic.Type) -> void:
	match type:
		Relic.Type.START_OF_COMBAT:
			player_handler.start_battle(char_stats)
			battle_ui.initialize_card_pile_ui()
		Relic.Type.END_OF_COMBAT:
			Events.battle_over_screen_requested.emit("Victorious!", BattleOverPanel.Type.WIN)
